package com.itany.corejava.code09_集合.set集合;

/**
 * @author 石小俊
 * @date 2023年05月06日 14:19
 */
public class User implements Comparable<User> {

    private String username;
    private int age;

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 比较方法,指定比较规则
     * 此时如果根据年龄进行升序排序
     *
     * @param user
     * @return
     */
    @Override
    public int compareTo(User user) {
        // 升序
        // 当前对象的年龄大于参数对象,返回值大于0
        if (this.age > user.getAge()) {
            return 1;
        } else if (this.age < user.getAge()) {
            return -1;
        } else {
            // 降序
            // 如果年龄相等, 可以根据用户名的长度进行比较
            if (this.username.length() > user.getUsername().length()) {
                return -1;
            } else if (this.username.length() < user.getUsername().length()) {
                return 1;
            }
            return 0;
        }
    }
}
